﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Dapper.Contrib.Extensions;

namespace SwaySway.Dao.Base
{
    public class BaseRepository<T> where T : class
    {
        public virtual bool Add(T t)
        {
            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                long result = conn.Insert<T>(t);
                return result > 0;
            }
        }

        public virtual bool Update(T t)
        {
            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                bool result = conn.Update<T>(t);
                return result;
            }
        }

        public virtual bool Delete(T t)
        {
            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                bool result = conn.Delete<T>(t);
                return result;
            }
        }

        public virtual T Get(int id)
        {
            return this.Get(id, new string[] { "*" });
        }

        public virtual T Get(int id, string[] field)
        {
            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                var p = new DynamicParameters();
                p.Add("@Id", id);

                StringBuilder strSql = new StringBuilder();
                strSql.Append($"select {string.Join(",", field)}");
                strSql.Append($" from {nameof(T)}");
                strSql.Append(" where Id = @Id");

                T result = conn.Query<T>(strSql.ToString(), p, commandType: CommandType.Text).FirstOrDefault();
                return result;
            }
        }

        public virtual IEnumerable<T> List(int offset, int next)
        {
            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                //OFFSET (15 * (50-1)) ROW FETCH NEXT 15 rows only
                StringBuilder strSql = new StringBuilder();
                strSql.Append($"select *");
                strSql.Append($" from {nameof(T)}");
                strSql.Append(" order by desc Id");
                strSql.Append($" offset {offset} row fetch next {next} rows only");
                IEnumerable<T> result = conn.Query<T>(strSql.ToString(), commandType: CommandType.Text);
                return result;
            }
        }
    }
}
